from . import settings
from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
from luffyapi.utils.log import get_logger
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

logger = get_logger('sms')


# 生成四位随机数字

def get_codes():
    import random
    codes = ''
    for i in range(4):
        codes += str(random.randint(0, 9))
    return codes


def send_message(phone_number, code, min=2):
    ssender = SmsSingleSender(settings.appid, settings.appkey)
    phone_numbers = []
    phone_numbers.append(phone_number)
    params = [code, min]  # 当模板没有参数时，`params = []`
    try:
        result = ssender.send_with_param(86, phone_numbers[0],
                                         settings.template_id, params, sign=settings.sms_sign, extend="", ext="")

        return result
    except HTTPError as e:
        print(e)
    except Exception as e:
        logger.error(f'手机号{phone_numbers[0]}短信发送失败')
        print(e)
